import axios from 'axios'
import { Message } from 'element-ui'
import * as auth from '@/utils/auth'
import router from '@/router'
import store from '@/store'

const request = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/' : process.env.BASE_API,
  timeout: process.env.NODE_ENV === 'development' ? 0 : 3000 // 使用本地后台接口时，不指定超时
})

request.interceptors.request.use(config => {
  const token = store.state.user.token
  if (token) {
    config.headers['X-Auth-Token'] = token
  }
  const method = config.method.toLowerCase()
  if (!config.headers['Content-Type'] && (method === 'post' || method === 'put' || method === 'patch')) {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  }
  return config
})

request.interceptors.response.use(resp => {
  const token = resp.headers['x-auth-token']
  if (token) {
    resp.data.token = token
  }
  if (resp.data.result === false) {
    return Promise.reject(resp.data)
  } else {
    return Promise.resolve(resp.data)
  }
}, err => {
  if (err.response) {
    const status = err.response.status
    if (status === 403) {
      auth.removeUser()
      router.push('/login')
    } else if (status === 401) {
      Message({
        message: err.response.data.message,
        type: 'error',
        duration: 3 * 1000
      })
    }
  }

  return Promise.reject(err)
})

export default request
